package com.bigknow.appstore.web.base.service;

import com.bigknow.appstore.web.framework.util.GlobalConstant;
import com.bigknow.appstore.web.framework.entity.IEntity;
import com.bigknow.appstore.web.framework.entity.ITreeEntity;

import java.util.*;

/**
 * Created by TwelveFoldEr on 2016/3/21.
 */
public class ServiceUtil {

    public static <T extends ITreeEntity> List<T> toTree(List<T> list) {
        List<T> result = new ArrayList<>();
        Map<String, ITreeEntity> map = new HashMap<>();
        // Prepared list map
        list.forEach(entity -> {
            map.put(entity.getCode(), entity);
        });

        // Find parent list
        list.forEach(entity -> {
            if (entity.getParentCode() == null || entity.getParentCode().trim().equals("")) {
                result.add(entity);
            } else {
                ITreeEntity parent = map.get(entity.getParentCode());
                if (parent != null) {
                    parent.getChildren().add(entity);
                    entity.setParentName(parent.getName());
                }
            }
        });

        return result;
    }

    public static <T extends ITreeEntity> List<T> sortTree(List<T> list) {
        Collections.sort(list, new Comparator<T>() {
            public int compare(T arg0, T arg1) {
                return arg0.getSort() - arg1.getSort();
            }
        });

        list.forEach(entity->{
            sortTree(entity.getChildren());
        });

        return list;
    }

    public static <T extends IEntity> String combineIds(List<T> list) {
        if (list == null || list.size() == 0) return "";
        StringBuilder sb = new StringBuilder();
        list.forEach(entity -> {
            sb.append(entity.getId()).append(GlobalConstant.COMBINATION_SEPARATOR);
        });

        return sb.toString().substring(0, sb.length() - 1);
    }
}
